﻿using System;
using TrainSimulator.Interfaces;
using System.Threading;

namespace TrainSimulator
{
    public class Dispatcher
    {
        private ITrain[] _trains;
        private bool _doRun; 

        public Dispatcher(ITrain[] trains)
        {
            _trains = trains;
        }

        internal void Create()
        {
            _doRun = true;
            Thread dThread = new Thread(Dispatch);
            dThread.Name = "Dispatch thread";
            dThread.Priority = ThreadPriority.Lowest;
            dThread.Start();
        }

        private void Dispatch()
        {
            while (_doRun)
            {
                foreach (var t in _trains)
                {
                    double secs = t.Engine.Interval / 1000;
                    t.UpdateState();
                    t.Engine.UpdatePosition(secs);
                }
            }
        }
    }
}
